package metu.tespit.session.course;

import java.util.Date;
import java.util.Iterator;

import metu.tespit.entitiy.accountManagement.User;
import metu.tespit.entity.course.Announcement;
import metu.tespit.session.EntityManager.ExtendedEntityHome;
import metu.tespit.session.util.Events;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.annotations.async.Asynchronous;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.faces.Renderer;

/**
 
 * @created May 23, 2012
 */
@Name("announcementHome")
public class AnnouncementHome extends ExtendedEntityHome<Announcement>{
	/**
	 * 
	 */
	private static final long serialVersionUID = -7768656870164264708L;

	@RequestParameter
	protected Long announcementId;

    @In(create=true)
    private Renderer renderer;

    private User toUser;

	@Override
	public Object getId()
	{
		if (announcementId == null)
		{
			return super.getId();
		}
		else
		{
			return announcementId;
		}
	}
	
	
	@In(create=true)
	CourseHome courseHome;

    @Transactional
	public String persistWithCourse(){

		if(courseHome!=null){
			this.instance.setCourse(courseHome.getInstance());
			this.instance.setCreationDate(new Date());
			courseHome.getInstance().getAnnouncements().add(this.instance);
            String outcome = super.persist();

            if (outcome.equalsIgnoreCase("persisted")) {
                raiseTransactionSuccessEvent(Events.ANNOUNCEMENT_CREATED, this.instance);
            }

            return outcome;
        }
		else{
			return "FAIL";
		}
	}

    @Observer(Events.ANNOUNCEMENT_CREATED)
    @Asynchronous
    public void sendMailToAllRegisteredStudents(Announcement announcement) {
    	System.out.println("\n *** ASYNC EMAIL!! ***\n");
        for (Iterator<User> iterator = announcement.getCourse().getStudents().iterator(); iterator.hasNext(); ) {
            try {
                toUser = iterator.next();
                renderer.render("/Mail/createAnnouncement.xhtml");
            } catch (Exception e) {
                // bu maili gonderirken hata alirsan sonrakini dene
                e.printStackTrace();
            }
        }
    }

    public User getToUser() {
        return toUser;
    }

    public void setToUser(User toUser) {
        this.toUser = toUser;
    }

    public Long getAnnouncementId() {
        return (Long)getId();
    }

    public void setAnnouncementId(Long announcementId) {
        this.setId(announcementId);
    }
}
